package com.gsafety.auth.controller;


import com.gsafety.common.core.constant.CacheConstants;
import com.gsafety.common.core.constant.TokenConstants;
import com.gsafety.common.core.domain.R;
import com.gsafety.common.core.utils.JwtUtils;
import com.gsafety.common.core.utils.StringUtils;
import com.gsafety.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

@RestController
public class AuthController {

    @Autowired
    private RedisService redisService;

    @GetMapping("/authenticate")
    public R<?> authenticate(@RequestHeader Map<String, String> headers,  HttpServletRequest  request) {
        // 实现鉴权逻辑，例如检查特定的token或者其他身份验证方法
        String token = getToken(request);

//        if (StringUtils.isEmpty(token)) {
//            return R.fail(HttpStatus.UNAUTHORIZED,"Not Authenticated");
//        }
//
//        Claims claims = JwtUtils.parseToken(token);
//        if (claims == null) {
//            return R.fail(HttpStatus.UNAUTHORIZED,"Not Authenticated");
//        }
//
//        String userkey = JwtUtils.getUserKey(claims);
//        boolean islogin = redisService.hasKey( CacheConstants.LOGIN_TOKEN_KEY + userkey);
//        if (!islogin) {
//            return R.fail(HttpStatus.UNAUTHORIZED,"Not Authenticated");
//        }
//        String userid = JwtUtils.getUserId(claims);
//        String username = JwtUtils.getUserName(claims);
//        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
//            return R.fail(HttpStatus.UNAUTHORIZED,"Not Authenticated");
//        }

        return R.ok("Authenticated");
    }


    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }


}
